//
//  KVNLineChartsView.m
//  Test1
//
//  Created by KelvinYeung on 15/8/10.
//  Copyright (c) 2015年 KelvinYeung. All rights reserved.
//

#import "KVNLineChartsView.h"

struct MyRGBValue{
    float r;
    float g;
    float b;
    float a;
};

@interface KVNLineChartsView()


@end

@implementation KVNLineChartsView



- (instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor whiteColor];
    //[self initSubViews];
    _lineChartTop = 30;
    _lineChartLeft = 20;
    _lineChartBottom = frame.size.height - 40;
    _lineChartRight = frame.size.width - 50;
    
    //颜色
    _firstItemUIColor = [UIColor orangeColor];
    _firstItemColor = [self changeUIColorToRGB:_firstItemUIColor];
    _secondItemUIColor = [UIColor purpleColor];
    _secondItemColor = [self changeUIColorToRGB:_secondItemUIColor];

    _firstItemName = @"";
    _secondItemName = @"";
    _firstItemNameLabel = [NSString stringWithFormat:@"◼︎%@",_firstItemName];
    _secondItemNameLabel = [NSString stringWithFormat:@"◼︎%@",_secondItemName];
    

    
    [self setInterval:24];
    [self calcMaxMin];
    return self;
}

- (void) initSubViews {

  

    

}


- (void) redrawCharts{
    [self calcMaxMin];
}

- (void) calcMaxMin{
    if(_firstItemArray != nil){
        _maxY = 0;
        _minY = 0;
        for (int i = 0; i <_firstItemArray.count; i++) {
            
            if ([_firstItemArray[i] isEqual:[NSNull null]]) {
                continue;
            }
            if(_maxY < [_firstItemArray[i] floatValue]){
                _maxY = [_firstItemArray[i] floatValue];
            }
        
            if(_firstItemArray[i]  != nil && _minY > [_firstItemArray[i] floatValue]){
                _minY = [_firstItemArray[i] floatValue];
            }
        }
    
        if(_secondItemArray != nil){
    
            for (int i = 0; i <_secondItemArray.count; i++) {
                if ([_secondItemArray[i] isEqual:[NSNull null]]) {
                    continue;
                }
                if( _maxY < [_secondItemArray[i] floatValue]){
                    _maxY = [_secondItemArray[i] floatValue];
                }
        
                if(_secondItemArray[i] != nil &&_minY > [_secondItemArray[i] floatValue]){
                _minY = [_secondItemArray[i] floatValue];
                }
            }
        }
        
        if(_minY == _maxY){
            _maxY++;
        }
    }

    NSLog(@"maxY:%f minY:%f",_maxY,_minY);
}


- (void) setInterval:(int)interval{

    
    _dateArray = [NSMutableArray array];
    //当前月份
    NSDate *currentDate = [NSDate date];
    NSCalendar * currentCalendar = [NSCalendar currentCalendar];
    
    NSDateComponents *compt = [currentCalendar components:(NSYearCalendarUnit|NSMonthCalendarUnit) fromDate:currentDate];

    [_dateArray addObject:[NSString stringWithFormat:@"%ld-%ld",(long)[compt year],(long)[compt month]]];
    
    NSDateComponents *intervalComponents = [[NSDateComponents alloc] init];
    [intervalComponents setMonth:-1];
    
    for (int i = 0 ; i<interval; i++ ){
        
        currentDate = [currentCalendar dateByAddingComponents:intervalComponents toDate:currentDate options:0];
        NSDateComponents *compt = [currentCalendar components:(NSYearCalendarUnit|NSMonthCalendarUnit) fromDate:currentDate];
        NSLog(@"%ld-%ld",(long)[compt year],(long)[compt month]);
        [_dateArray addObject:[NSString stringWithFormat:@"%ld-%ld",(long)[compt year],(long)[compt month]]];
        
    }

    

}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
   
    [self drawNetGridLines:rect];
    
}



- (void) drawNetGridLines:(CGRect)rect{

    _firstItemNameLabel = [NSString stringWithFormat:@"◼︎%@",_firstItemName];
    _secondItemNameLabel = [NSString stringWithFormat:@"◼︎%@",_secondItemName];
    
    // Drawing code
    //获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 设置线段宽度
    CGContextSetLineWidth(ctx, 2);
    // 设置线段头尾部的样式
    CGContextSetLineCap(ctx, kCGLineCapRound);
    
    // 设置线段转折点的样式
    
    CGContextSetLineJoin(ctx, kCGLineJoinRound);
    
    /**  第1根线段  **/
    // 设置颜色
    CGContextSetRGBStrokeColor(ctx, 200/255.0, 200/255.0, 200/255.0, 1);
    // 设置一个起点
    CGContextMoveToPoint(ctx, _lineChartLeft , _lineChartBottom );
    // 添加一条线段到(100, 100)
    CGContextAddLineToPoint(ctx, _lineChartRight, _lineChartBottom);
    CGContextAddLineToPoint(ctx, _lineChartRight, _lineChartTop -15);
    // 渲染一次
    CGContextStrokePath(ctx);
    
    
    /**  线框顶部  **/
    // 设置线段宽度
    CGContextSetLineWidth(ctx, 1);
    // 设置线段头尾部的样式
    CGContextSetLineCap(ctx, kCGLineCapRound);
    // 设置线段转折点的样式
    CGContextSetLineJoin(ctx, kCGLineJoinBevel);
    // 设置颜色
    CGContextSetRGBStrokeColor(ctx, 200/255.0, 200/255.0, 200/255.0, 1);
    // 设置一个起点
    CGContextMoveToPoint(ctx, _lineChartLeft , _lineChartTop );
    // 添加一条线段到(100, 100)
    CGContextAddLineToPoint(ctx, _lineChartRight,_lineChartTop);
    // 渲染一次
    CGContextStrokePath(ctx);
    
    
    
    
    //画12条竖线
    int _xlineCont = _firstItemArray ==nil? 12:(int)_firstItemArray.count;
    CGFloat deltaX = (_lineChartRight - _lineChartLeft)/_xlineCont;
    NSLog(@"坚线：：：deltaX:%f",deltaX);
    
    // 设置线段宽度
    CGContextSetLineWidth(ctx, 1);
    
    
    for (int i = 0; i<=_xlineCont; i++) {
        if(i%(2*(_xlineCont/12))==0){
            CGContextSetRGBStrokeColor(ctx, 200/255.0, 200/255.0, 200/255.0, 1);
            CGContextMoveToPoint(ctx, _lineChartRight - deltaX*i , _lineChartBottom );
            CGContextAddLineToPoint(ctx, _lineChartRight - deltaX*i, _lineChartTop);
            CGContextStrokePath(ctx);
            //画文字
            [_dateArray[i] drawAtPoint:CGPointMake(_lineChartRight - deltaX*i-13 , _lineChartBottom+2) withFont:[UIFont systemFontOfSize:8]];
        
        }
    }
    
    
    //画刻度
    CGFloat deltaY = (_lineChartBottom-_lineChartTop)/5.0;
    // 设置线段宽度
    CGContextSetLineWidth(ctx, 2);
    for (int i = 0; i<6; i++) {
            CGContextSetRGBStrokeColor(ctx, 200/255.0, 200/255.0, 200/255.0, 1);
            CGContextMoveToPoint(ctx, _lineChartRight , _lineChartBottom - deltaY*i );
            CGContextAddLineToPoint(ctx, _lineChartRight -5, _lineChartBottom - deltaY*i);
            CGContextStrokePath(ctx);
        
            //画文字
            NSString * str = [NSString stringWithFormat:@"%d",(int)ceil(i*(_maxY-_minY)/5.0+_minY)];
            [str drawAtPoint:CGPointMake(_lineChartRight+2 , _lineChartBottom - 10 - deltaY*i ) withFont:[UIFont systemFontOfSize:12]];
        
    }

    
    //画折线
    // 设置一个起点
    BOOL isPreValueisNull = YES;
    if(_firstItemArray != nil){
        
        CGContextSetRGBStrokeColor(ctx, _firstItemColor.r, _firstItemColor.g, _firstItemColor.b, _firstItemColor.a);
       
        for (int i = 0; i<_firstItemArray.count; i++) {
            if ([_firstItemArray[_firstItemArray.count-i-1] isEqual: [NSNull null]]) {
                isPreValueisNull = YES;
            }else{
                
                if (isPreValueisNull) {
                    CGContextMoveToPoint(ctx, _lineChartRight, _lineChartBottom -  ([_firstItemArray[_firstItemArray.count-i-1] floatValue] - _minY)* deltaY/((_maxY-_minY)/5.0));
                    isPreValueisNull = NO;
                }else{
                    
                    CGContextAddLineToPoint(ctx, _lineChartRight - deltaX*i , _lineChartBottom -  ([_firstItemArray[_firstItemArray.count-i-1] floatValue] - _minY)* deltaY/((_maxY-_minY)/5.0) );
                    CGContextAddEllipseInRect(ctx, CGRectMake(_lineChartRight - deltaX*i -1.5, _lineChartBottom -  ([_firstItemArray[_firstItemArray.count - i - 1] floatValue] - _minY)* deltaY/((_maxY-_minY)/5.0)-1.5, 3, 3));
                    
                }
                
            }
            
            
        }
        
        CGContextStrokePath(ctx);
    }
    
    //house折线
    // 设置颜色
    CGContextSetRGBStrokeColor(ctx, _secondItemColor.r, _secondItemColor.g, _secondItemColor.b, _secondItemColor.a);

    isPreValueisNull=YES;
    if(_secondItemArray != nil)
    {
        
        
        for (int i = 0; i<_secondItemArray.count; i++) {
            
            if ([_secondItemArray[_secondItemArray.count-i-1] isEqual:[NSNull null]]) {
                isPreValueisNull = YES;
            }else{
            
                if (isPreValueisNull == YES) {
                    CGContextMoveToPoint(ctx, _lineChartRight, _lineChartBottom -  ([_secondItemArray[_secondItemArray.count-i-1] floatValue] - _minY)* deltaY/((_maxY-_minY)/5.0 ));
                    isPreValueisNull = NO;
                }else{
                
                    // 添加一条线段到(100, 100)
                    CGContextAddLineToPoint(ctx, _lineChartRight - deltaX*i , _lineChartBottom -  ([_secondItemArray[_secondItemArray.count - i - 1] floatValue] - _minY)* deltaY/((_maxY-_minY)/5.0 ));
            
                    CGContextAddEllipseInRect(ctx, CGRectMake(_lineChartRight - deltaX*i-1.5, _lineChartBottom -  ([_secondItemArray[_secondItemArray.count - i - 1] floatValue] - _minY)* deltaY/((_maxY-_minY)/5.0 )-1.5, 3, 3));
                }
             }
        }
        CGContextStrokePath(ctx);
    
    }

    //颜色指示
    [_firstItemNameLabel drawAtPoint:CGPointMake(_lineChartLeft + 10, _lineChartBottom + 15) withAttributes:@{NSForegroundColorAttributeName:_firstItemUIColor,NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    //颜色指示
    [_secondItemNameLabel drawAtPoint:CGPointMake(_lineChartLeft + 80, _lineChartBottom + 15) withAttributes:@{NSForegroundColorAttributeName:_secondItemUIColor,NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    
    [@"元/m" drawAtPoint:CGPointMake(_lineChartRight, _lineChartTop - 25) withAttributes:@{NSForegroundColorAttributeName:[UIColor grayColor],NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    
    [@"2" drawAtPoint:CGPointMake(_lineChartRight+30, _lineChartTop - 25) withAttributes:@{NSForegroundColorAttributeName:[UIColor grayColor],NSFontAttributeName:[UIFont systemFontOfSize:8]}];
    
    
}


//将UIColor转换为RGB值
- (struct MyRGBValue) changeUIColorToRGB:(UIColor *)color
{
    
    struct MyRGBValue  myRGBValue;
    /*
    const CGFloat * com = CGColorGetNumberOfComponents(color.CGColor);
    NSLog(@"Red: %f", com[0]);
    NSLog(@"Green: %f", com[1]);
    NSLog(@"Blue: %f", com[2]);
     NSLog(@"Blue: %f", com[3]);
    myRGBValue.r = com[0];
    myRGBValue.g = com[1];
    myRGBValue.b = com[2];
    myRGBValue.a = com[3];
     */
    /*
    //获得RGB值描述
    NSString *RGBValue = [NSString stringWithFormat:@"%@",color];
    NSLog(@"changeUIColor:%@",RGBValue);
    //将RGB值描述分隔成字符串
    NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
    //获取红色值
    myRGBValue.r = [[RGBArr objectAtIndex:1] intValue] * 255;
    //获取绿色值
    myRGBValue.g = [[RGBArr objectAtIndex:2] intValue] * 255;
    //获取蓝色值
    myRGBValue.b = [[RGBArr objectAtIndex:3] intValue] * 255;
     */
    
    
    
   
    size_t numComponents = CGColorGetNumberOfComponents(color.CGColor);
    
    if (numComponents == 4)
    {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        myRGBValue.r = components[0];
        myRGBValue.g = components[1];
        myRGBValue.b = components[2];
        myRGBValue.a = components[3];
    }
    return myRGBValue;
}



@end
